package com.scau.yangsuiyu.estore.controller.seller;

import com.alibaba.fastjson.JSONObject;
import com.jfoenix.controls.JFXComboBox;
import com.scau.yangsuiyu.estore.controller.myComponent.ShopGoodsHBox;
import com.scau.yangsuiyu.estore.controller.seller.manageShop.ShopGoodsManagePane;
import com.scau.yangsuiyu.estore.dababases.dao.CategoryDao;
import com.scau.yangsuiyu.estore.dababases.dao.GoodsPhotoDao;
import com.scau.yangsuiyu.estore.dababases.dao.ShopDao;
import com.scau.yangsuiyu.estore.dababases.entity.Goods;
import com.scau.yangsuiyu.estore.dababases.entity.GoodsPhoto;
import com.scau.yangsuiyu.estore.service.GoodsService;
import com.scau.yangsuiyu.estore.util.FormValidate;
import javafx.collections.FXCollections;
import javafx.fxml.FXML;
import javafx.fxml.FXMLLoader;
import javafx.fxml.Initializable;
import javafx.scene.Scene;
import javafx.scene.control.*;
import javafx.scene.image.Image;
import javafx.scene.image.ImageView;
import javafx.scene.layout.AnchorPane;
import javafx.scene.layout.HBox;
import javafx.stage.FileChooser;
import javafx.stage.Stage;

import javax.imageio.ImageIO;
import java.awt.image.BufferedImage;
import java.io.File;
import java.io.IOException;
import java.net.URL;
import java.util.*;

/**
 * @author suiyu_yang
 * @description 编辑/添加商品的Pane
 * @date 2019-06-10 09:18
 * @email suiyu_yang@163.com
 */
public class EditGoodsPane extends AnchorPane implements Initializable {
    private Stage stage;
    private ShopGoodsHBox shopGoodsHBox;
    private ShopGoodsManagePane shopGoodsManagePane;

    private Goods goods;

    private FormValidate<TextInputControl> nullValueValidate = new FormValidate<>();
    private FormValidate<TextInputControl> regNumValidate = new FormValidate<>();

    //    private List<GoodsPhoto> goodsPhotos = new ArrayList<>();
    private List<GoodsPhoto> newGoodsPhotos = new ArrayList<>();
    private Map<ImageView, GoodsPhoto> photoMap = new HashMap<>();

    @FXML
    private Label titleLabel;

    @FXML
    private JFXComboBox<String> categoryCB;

    @FXML
    private Label deliveryPriceError;

    @FXML
    private Label inventoryError;

    @FXML
    private Label priceError;

    @FXML
    private Label promotionalPriceError;

    @FXML
    private Label profileError;

    @FXML
    private Label nameError;

    @FXML
    private TextArea profileTA;

    @FXML
    private TextField deliveryPriceTF;

    @FXML
    private TextField inventoryTF;

    @FXML
    private TextField priceTF;

    @FXML
    private TextField promotionalPriceTF;

    @FXML
    private TextField nameTF;

    @FXML
    private HBox imagesHBox;

    @FXML
    private HBox addPhotoHBox;

    public EditGoodsPane(ShopGoodsHBox shopGoodsHBox) {
        this.shopGoodsHBox = shopGoodsHBox;
        loadFXML();
    }

    public EditGoodsPane(ShopGoodsManagePane shopGoodsManagePane) {
        this.shopGoodsManagePane = shopGoodsManagePane;
        loadFXML();
    }

    public void showPane() {
        stage = new Stage();
        stage.setScene(new Scene(this));

        stage.show();
    }

    private void loadFXML() {
        FXMLLoader fxmlLoader = new FXMLLoader(getClass().getResource("/view/buyer/EditGoodsPane.fxml"));
        fxmlLoader.setController(this);
        fxmlLoader.setRoot(this);
        try {
            fxmlLoader.load();
        } catch (IOException e) {
            e.printStackTrace();
        }
    }

    @Override
    public void initialize(URL location, ResourceBundle resources) {
        installFormValidate();
        updateCategoryCB();
        if (shopGoodsHBox != null) {
            titleLabel.setText("修改商品");
            goods = shopGoodsHBox.getGoods();
            setGoodsToUI();
        } else {
            titleLabel.setText("添加商品");
            addPhotoHBox.setVisible(false);
            goods = new Goods();
        }

    }


    @FXML
    private void saveClick() {
        if (categoryCB.getValue() == null) {
            new Alert(Alert.AlertType.ERROR, "请选择商品类别！").showAndWait();
        } else {
            if (nullValueValidate.isValid() && regNumValidate.isValid()) {
                if (shopGoodsHBox != null) {
                    modifyGoods();
                } else {
                    addGoods();
                }
            }
        }

    }

    @FXML
    private void choosePhotoClick() {
        if (photoMap.size() < 3) { //最多只能选择3张图片
            FileChooser photoChooser = new FileChooser();
            photoChooser.setTitle("请选择你的头像");
            photoChooser.getExtensionFilters().addAll(
                    new FileChooser.ExtensionFilter("所有图片", "*.*"),
                    new FileChooser.ExtensionFilter("JPG", "*.jpg"),
                    new FileChooser.ExtensionFilter("PNG", "*.png")
            );

            Stage stage = new Stage();
            File choosePhoto = photoChooser.showOpenDialog(stage);

            String photoUrl = choosePhoto.getAbsolutePath();
            ImageView imageView = loadImage(photoUrl);

            if (imageView != null) {
                GoodsPhoto goodsPhoto = new GoodsPhoto();
                goodsPhoto.setGoods(goods);
                goodsPhoto.setPhotoUrl(photoUrl);

                newGoodsPhotos.add(goodsPhoto);

                photoMap.put(imageView, goodsPhoto);

                updateImagesHBox();
            }
        } else {
            new Alert(Alert.AlertType.ERROR, "最多只能选择3张图片!").showAndWait();
        }
    }

    /**
     * 修改商品操作
     */
    private void modifyGoods() {
        getGoodsFromUI();

        List<GoodsPhoto> currentGoodsPhotos = new ArrayList<>();
        for (Map.Entry<ImageView, GoodsPhoto> entry : photoMap.entrySet()) {
            currentGoodsPhotos.add(entry.getValue());
        }
        System.out.println("currentGoodsPhotos:" + currentGoodsPhotos.size());
        goods.setGoodsPhotoList(currentGoodsPhotos);

//        for (GoodsPhoto goodsPhoto : newGoodsPhotos) {
//            new GoodsPhotoDao().insert(goodsPhoto);
//        }

        JSONObject resultJson = new GoodsService(goods).updateGoods();

        new Alert(Alert.AlertType.INFORMATION, resultJson.getString("result")).showAndWait();

        shopGoodsHBox.updateGoodsToUI();
        stage.close();
    }

    /**
     * 添加商品操作
     */
    private void addGoods() {
        getGoodsFromUI();
        goods.setShop(shopGoodsManagePane.getShop());
        JSONObject resultJson = new GoodsService(goods).addGoods();

//        for (GoodsPhoto goodsPhoto : newGoodsPhotos) {
//            goodsPhoto.setGoods(resultJson.getObject("goods", Goods.class));
//            new GoodsPhotoDao().insert(goodsPhoto);
//        }

        new Alert(Alert.AlertType.INFORMATION, resultJson.getString("result")).showAndWait();

        new ShopDao().update(shopGoodsManagePane.getShop());

        shopGoodsManagePane.updateUI();
        stage.close();
    }


    private void getGoodsFromUI() {
        goods.setCategory(new CategoryDao().getCategoryByName(categoryCB.getValue()));
        goods.setGoodsName(nameTF.getText());
        goods.setProfile(profileTA.getText());
        goods.setDeliveryPrice(Double.parseDouble(deliveryPriceTF.getText()));
        goods.setPrice(Double.parseDouble(priceTF.getText()));
        goods.setPromotionPrice(Double.parseDouble(promotionalPriceTF.getText()));
        goods.setInventory(Integer.parseInt(inventoryTF.getText()));

    }

    private ImageView loadImage(String url) {
        File file = new File(url);
        ImageView photoImageView = new ImageView();
        BufferedImage bufferedImage = null;
        try {
            bufferedImage = ImageIO.read(file);
        } catch (IOException e) {
            new Alert(Alert.AlertType.ERROR, "请选择正确的图片！").showAndWait();
        }

        if (bufferedImage != null) {
            photoImageView.setImage(new Image("file:" + url));
            photoImageView.setFitHeight(100);
            photoImageView.setFitWidth(100);

            photoImageView.setOnMouseClicked(e -> {
                Optional optional = new Alert(Alert.AlertType.CONFIRMATION, "是否删除该图片？").showAndWait();
                if (optional.isPresent() && optional.get() == ButtonType.OK) {
                    if (newGoodsPhotos.contains(photoMap.get(photoImageView))) {
                        newGoodsPhotos.remove(photoMap.get(photoImageView));
                    } else {
                        new GoodsPhotoDao().delete(photoMap.get(photoImageView));
                    }
                    photoMap.remove(photoImageView);
                    updateImagesHBox();
                }
            });
            return photoImageView;
        } else {
            return null;
        }
    }

    private void updateImagesHBox() {
        imagesHBox.getChildren().clear();

        imagesHBox.getChildren().addAll(photoMap.keySet());
    }

    /**
     * 读取数据库中的类别，并更新CategoryCB
     */
    private void updateCategoryCB() {
        List<String> categoryNameList = new CategoryDao().getAllCategoryName();

        categoryCB.setItems(FXCollections.observableArrayList(categoryNameList));

    }


    /**
     * 当，当前为修改商品时，将原有商品的信息填充至UI中
     */
    private void setGoodsToUI() {
        categoryCB.setPromptText(goods.getCategory().getName());
        nameTF.setText(goods.getGoodsName());
        priceTF.setText(goods.getPrice() + "");
        promotionalPriceTF.setText(goods.getPromotionPrice() + "");
        deliveryPriceTF.setText(goods.getDeliveryPrice() + "");
        inventoryTF.setText(goods.getInventory() + "");
        profileTA.setText(goods.getProfile());

//        goodsPhotos.addAll(goods.getGoodsPhotoList());
        for (GoodsPhoto goodsPhoto : goods.getGoodsPhotoList()) {
            ImageView imageView = loadImage(goodsPhoto.getPhotoUrl());
            photoMap.put(imageView, goodsPhoto);
        }

        updateImagesHBox();
    }

    /**
     * 为错误信息Label和TextField配置表单验证类
     */
    private void installFormValidate() {

        TextInputControl[] requireTFs = {nameTF, profileTA};
        Label[] reqLabels = {nameError, profileError};
        nameError.setText("商品名不能为空");
        profileError.setText("商品简介不能为空");
        nullValueValidate.installRequireValidation(requireTFs, reqLabels);

        TextInputControl[] regTFs = {priceTF, promotionalPriceTF, deliveryPriceTF, inventoryTF};
        Label[] regLabels = {priceError, promotionalPriceError, deliveryPriceError, inventoryError};
        deliveryPriceError.setText("数字格式错误！");
        inventoryError.setText("数字格式错误！");
        priceError.setText("数字格式错误！");
        promotionalPriceError.setText("数字格式错误！");
        regNumValidate.installRegularValidation(regTFs, FormValidate.DECIMAL_REG, regLabels);

    }
}
